<template>
  <form class="validate-form-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent,onUnmounted } from 'vue';
//引入全局事件总线库mitt
import mitt from 'mitt';
//mitt使用规则
type ValidateFunc = () => boolean
type Events = {'form-item-created': ValidateFunc}
export const emitter = mitt<Events>()
export default defineComponent({
  emits:['form-submit'],
  setup(props, ctx) {
    let funcArr: ValidateFunc[] = []
    const submitForm = ()=>{
      const result = funcArr.map(func => func()).every(result => result)
      ctx.emit('form-submit',result)
    }
    const callback = (func?:ValidateFunc) =>{
      if(func){
        funcArr.push(func)
      }
    }

    emitter.on('form-item-created',callback)
    onUnmounted(()=>{
      emitter.off('form-item-created',callback)
      funcArr =[]
    })
    return {
      submitForm
    }
  },
  mounted(){
    // this.$on('item-created',()=>{

    // })
  }
})
</script>

<style>

</style>